//
//  YHShip.cpp
//  ThunderWarriors
//
//  Created by mac on 13-6-22.
//
//

#include "YHShip.h"
#include "YHGameDefine.h"
#include "YHBullet.h"
#include "YHGameLayerFight.h"
#include "YHEffect.h"

static const int kShipLife = 5;

YHShip::YHShip(){
    m_HP = kShipLife;
    m_isActive = true;
}

YHShip::~ YHShip(){
    
}

void YHShip::destroy(){
    YHEffect* effect = YHEffect::create();
    effect->explode(this->getParent(), this->getPosition());
}

bool YHShip::init(){
    if (! CCSprite::init()) {
        return false;
    }
    
    CCTexture2D* shipTexture =  CCTextureCache::sharedTextureCache()->addImage("ship01.png");
    
    this->initWithTexture(shipTexture, CCRectMake(0, 0, 60, 38));
    CCSpriteFrame* frame0 = CCSpriteFrame::createWithTexture(shipTexture, CCRectMake(0, 0, 60, 38));
    CCSpriteFrame* frame1 = CCSpriteFrame::createWithTexture(shipTexture, CCRectMake(60, 0, 60, 38));
    CCArray* arraySpriteFrames = CCArray::create(frame0,  frame1, NULL);
    CCAnimation* animation = CCAnimation::createWithSpriteFrames(arraySpriteFrames, 0.2);
    CCAnimate* animate = CCAnimate::create(animation);
    this->runAction(CCRepeatForever::create(animate));
    
    this->schedule(schedule_selector(YHShip::shoot), 0.2);
    
    return true;
}

void YHShip::hurt(){
    if (m_HP > 0) {
         m_HP -=1;
    }
    if (m_HP <= 0) {
        m_isActive = false;
    }
}

CCRect YHShip::getCollideCrect(){
    return this->boundingBox();
}

void YHShip::shoot(float dt){
    
    if (this->getParent() == NULL) {
        return;
    }
    else{
        CCSpriteBatchNode* shipBullets = YHGameLayerFight::sharedGameLayerFight()->getShipBullets();
        for (int i = 0; i < 2; i ++) {
            int offset = ((i == 0)? -13:13);
            YHBullet* bullet = YHBullet::create(s_play_bullet, kPlayBulletSpeed);
            CCPoint pos = this->getPosition();
            pos.x = pos.x + offset;
            pos.y = pos.y + 3 + getContentSize().height*0.3;
            bullet->setPosition(pos);
            shipBullets->addChild(bullet);
        }
    }
}